<template>
  <div class="height-100-percent">
    <div
      style="position:fixed;top:0;width:100%;background:#555;color:#fff;"
      class="flex flex-row flex-middle flex-end"
      v-if="showNotification"
    >
      <div>点击右上角</div>
      <van-icon name="weapp-nav" style="padding:0 10px" />
      <div class="padding-right-10">添加到我的小程序</div>
    </div>
    <div class="flex flex-column height-100-percent">
      <div
        class="flex flex-row flex-end padding-right-10 padding-top-20 padding-bottom-20"
        :class="earnings>0?'bg-red':'bg-green'"
      >
        <div class="flex flex-column flex-center text-align-center white">
          <div class="font-size-13 flex flex-row flex-end flex-middle">
            <div>实时盈亏估算（元）</div>
            <van-icon
              @click="showEarning = !showEarning"
              class="font-size-17"
              :name="showEarning ? 'eye-o': 'closed-eye'"
            />
          </div>
          <div
            class="font-size-32 margin-10"
            style="min-height:37px"
          >{{showEarning ? earnings : '****'}}</div>
          <!-- <span class="font-size-13">收益率：{{showEarning? '%': '****'}}</span> -->
        </div>
      </div>
      <div class="grid text-align-center bold bg-white line margin-top-10">
        <div class="text-align-left padding-left-10">
          基金名称
          <span class="iconfont icon-pan bolder"></span>
        </div>
        <div class="flex flex-row flex-middle" @click="sortData('gszzl')">
          净值估算
          <van-icon name="sort" :color="sort=='gszzl'?'#ee5f5b':''" />
        </div>
        <!-- <div class="flex flex-row flex-middle">实时图</div> -->
        <div class="flex flex-row flex-middle" @click="sortData('earning')">
          盈亏估算
          <van-icon name="sort" :color="sort=='earning'?'#ee5f5b':''" />
        </div>
      </div>

      <van-pull-refresh class="flex-1 overflow-auto" v-model="isLoading" @refresh="onRefresh">
        <div
          @click="showEditFund(item)"
          class="grid texit-algn-center bold bg-white border-bottom padding-top-5 padding-bottom-5"
          v-for="item in datas"
          :key="item.code"
        >
          <div class="text-align-left padding-left-10">
            <div class="flex flex-row flex-nowrap">
              <div class="flex flex-column flex-1">
                <div class="font-size-15 line-height-15">{{item.name}}</div>
                <div class="font-size-14">{{item.code}}</div>
              </div>
            </div>
          </div>
          <div class="text-align-center" :class="item.earning>0?'color-red': 'color-green'">
            <div class="font-size-15 line-height-15">{{item.gsz}}</div>
            <div class="font-size-14">{{item.gszzl}}%</div>
          </div>
          <div class="text-align-center flex-column flex-middle">
            <div
              class="font-size-15 line-height-15"
              :class="item.earning>0?'color-red': 'color-green'"
            >{{item.earning}}</div>
            <div class="real_earningText" v-if="item.isUpdate">已更新</div>
          </div>
        </div>
      </van-pull-refresh>

      <div class="bg-white flex flex-row flex-nowrap padding-10">
        <van-button
          @click="showAddFund"
          plain
          type="primary"
          class="flex flex-middle flex-center flex-1 addFundButton margin-right-5"
        >添加基金</van-button>
      </div>
    </div>

    <van-dialog
      v-model="showAddFundDialog"
      @confirm="addFundConfirm"
      :title="editReadOnly ? '持有':'添加'"
      show-cancel-button
    >
      <div v-if="editReadOnly" class="flex flex-row flex-middle flex-end" @click="showDeleteFund">
        <van-icon name="delete" :color="'gray'" />
        <span class="padding-left-10 padding-right-10" style="color:gray">删除</span>
      </div>
      <van-field
        v-model="fund.fundCode"
        type="number"
        :disabled="editReadOnly"
        label="编码"
        placeholder="请输入基金编码"
      />
      <van-field
        v-model="fund.fundName"
        v-if="editReadOnly"
        disabled
        label="名称"
        placeholder="请输入基金编码"
      />
      <van-field v-model="fund.fundQuotient" type="digit" label="份额" placeholder="请输入份额" />
    </van-dialog>
  </div>
</template> 

<script>
import { Dialog } from 'vant'

import { getFund } from '@/api'
import { http, showWarningToast, showSuccessToast, showLoading, hideLoading } from '~utils'

export default {
  data () {
    return {
      showNotification: false, // 顶部
      showEarning: true,
      showAddFundDialog: false, // 添加基金弹出层
      editReadOnly: false,
      fund: {
        fundCode: '',
        fundName: '',
        fundQuotient: ''
      },
      sort: '',
      sortValue: '',
      datas: [],
      earnings: '',
      isLoading: false
    }
  },
  components: {
    [Dialog.Component.name]: Dialog.Component,
  },
  async mounted () {
    document.title = '计算器'
    this.getData()
  },
  methods: {
    async getData (refresh) {
      showLoading()
      // 先检查本地是否有缓存
      let zixuanjijins = localStorage.getItem('zixuanjijins')
      if (zixuanjijins) {
        zixuanjijins = JSON.parse(zixuanjijins)
      }
      if (!zixuanjijins || !zixuanjijins.length || refresh) {
        // 若没有则 从数据库查询
        zixuanjijins = await this.getZixuan() || []
      }
      hideLoading()

      // 调试模式
      // let { result } = await wx.cloud.callFunction({
      //   name: 'getUserFund',
      //   data: {
      //     OPENID: 'oCrx85JL5ObHLF1rejP54n6FF3zY'
      //   }
      // })
      // this.datas = []
      await this.fmtData(zixuanjijins)

      // // 计算盈亏估算
      let earnings = 0
      this.datas.forEach(item => {
        let earning = Number(item.earning)
        if (!isNaN(earning)) {
          earnings += earning
        }
      })
      this.earnings = Number(earnings).toFixed(2)
    },
    async getZixuan () {
      let { result } = await this.$cloudbase.callFunction({
        name: 'getMyFund',
        data: {
          OPENID_WEB: this.$openid
        }
      })
      let zixuanjijins = result.data || []
      // 并存入缓存
      localStorage.setItem('zixuanjijins', JSON.stringify(zixuanjijins))

      return zixuanjijins
    },
    async fmtData (data = []) {
      if (!data.length) {
        return data
      }
      let result = []
      let codes = data.filter(item => typeof item.code !== 'undefined').map(item => item.code).join(',')

      let jjInfos = await http({
        url: `https://fundmobapi.eastmoney.com/FundMNewApi/FundMNFInfo?pageIndex=1&pageSize=50&plat=Android&appType=ttjj&product=EFund&Version=1&deviceid=ssdfsdfsdf&Fcodes=${codes}`,
        method: 'get',
        loading: false
      })

      let jjDatas = jjInfos.Datas
      let jjExpansion = jjInfos['Expansion']

      let jjDatasObject = {}
      let updateCodes = []

      jjDatas.forEach(item => {
        jjDatasObject[item.FCODE] = item
        if (item.PDATE == jjExpansion.GZTIME) {
          updateCodes.push(item.FCODE) // 记录已更新数据
        }
      })

      let updatedFunds = await this.getUpdateFund(updateCodes)

      for (let item of data) {
        if (!item.code) {
          continue
        }

        let jjData = jjDatasObject[item.code] || {}

        let isUpdate = jjData.PDATE == jjExpansion.GZTIME
        let yesterday_jingzhi = Number(jjData.NAV) // 昨天的净值
        let current_jingzhi = Number(jjData.GSZ) // 当前估值
        let zzl = jjData.GSZZL // 增长率

        if (isUpdate) {
          // 说明更新了
          // 通过接口请求昨天的净值
          let fund = updatedFunds[item.code] || {}
          yesterday_jingzhi = Number(fund.dwjz) // fundmoba接口的净值已更新为今天，取fundgz接口的昨天净值
          current_jingzhi = Number(jjData.NAV) // 当前估值更新为实际净值
          zzl = Number((current_jingzhi - yesterday_jingzhi) / yesterday_jingzhi * 100).toFixed(2)
        }

        let earning = Number(current_jingzhi - yesterday_jingzhi) * Number(item.quotient).toFixed(2) // 收益

        result.push({
          ...item,
          name: jjData.SHORTNAME,
          code: jjData.FCODE || item.code,
          gsz: isNaN(current_jingzhi) ? '--' : current_jingzhi,
          gszzl: isNaN(zzl) ? '--' : zzl,
          earning: isNaN(earning) ? '--' : Number(earning).toFixed(2),
          isUpdate: isUpdate && !isNaN(earning)
        })
      }

      if (this.sort && this.sortValue) {
        let sortKey = this.sort

        let data = result.filter(item => item[sortKey] != '--') || []
        let noData = result.filter(item => item[sortKey] == '--') || []

        if (this.sortValue == 'asc') {
          data = data.sort((a, b) => Number(a[sortKey]) - Number(b[sortKey]))
        } else if (this.sortValue == 'desc') {
          data = data.sort((a, b) => Number(b[sortKey]) - Number(a[sortKey]))
        }

        data.push(...noData)
        result = data
      }

      this.datas = result
      return result
    },
    async getUpdateFund (codes) {
      let obj = {}
      for (let code of codes) {
        let res = await getFund(code)
        obj[res.fundcode] = res
      }
      return obj
    },
    showAddFund () {
      this.editReadOnly = false
      this.fund = {
        fundCode: '',
        fundQuotient: '',
        fundName: '',
        fundId: ''
      }
      this.showAddFundDialog = true
    },
    async addFundConfirm () {
      if (this.editReadOnly) {
        this.editFundConfirm()
        return
      }
      if (!this.fund.fundCode || !this.fund.fundQuotient) {
        // 反之提示
        showWarningToast('请输入基金编码及份额')
        return
      }

      if (isNaN(Number(this.fund.fundQuotient))) {
        showWarningToast('份额请输入数字')
        return
      }

      // 先检查是否已存在
      let isExist = this.datas.find(item => item.code == this.fund.fundCode)
      if (isExist) {
        showWarningToast('该基金已添加')
        return
      }

      await getFund(this.fund.fundCode) || {} // 检查基金是否存在

      let { result } = await this.$cloudbase.callFunction({
        name: 'addMyFund',
        data: {
          fundCode: this.fund.fundCode,
          fundQuotient: this.fund.fundQuotient,
          OPENID_WEB: this.$openid
        }
      })


      if (result.error) {
        showWarningToast(result.error)
        return
      }

      // 添加成功，刷新数据
      showSuccessToast()
      this.getData(true)

    },
    showEditFund (item) {
      this.editReadOnly = true
      this.showAddFundDialog = true
      this.fund = {
        fundCode: item.code,
        fundQuotient: item.quotient,
        fundName: item.name,
        fundId: item._id
      }
    },
    async editFundConfirm () {
      if (!this.fund.fundQuotient) {
        // 反之提示
        showWarningToast('请输入份额')
        return
      }

      if (isNaN(Number(this.fund.fundQuotient))) {
        showWarningToast('份额请输入数字')
        return
      }

      // 执行修改
      let { result } = await this.$cloudbase.callFunction({
        name: 'editMyFund',
        data: {
          fundQuotient: this.fund.fundQuotient,
          fundId: this.fund.fundId,
          OPENID_WEB: this.$openid
        }
      })

      if (result.error) {
        showWarningToast(result.error)
        return
      }

      showSuccessToast()
      this.getData(true)
    },
    showDeleteFund () {
      Dialog.confirm({
        title: '提示',
        message: '是否确认要删除？',
      }).then(async () => {
        this.showAddFundDialog = false
        await this.$cloudbase.callFunction({
          name: 'deleteMyFund',
          data: {
            fundQuotient: this.fund.fundQuotient,
            fundId: this.fund.fundId
          }
        })
        showSuccessToast('删除成功')
        this.getData(true)
      })
    },
    async onRefresh () {
      this.isLoading = true
      await this.getData()
      this.isLoading = false
    },
    getNextSortValue () {
      if (this.sortValue == '') {
        // 先倒叙
        return 'desc'
      }

      if (this.sortValue == 'desc') {
        // 顺序
        return 'asc'
      }

      if (this.sortValue == 'asc') {
        // 清空排序
        return ''
      }
    },
    sortData (key) {
      let sortValue = ''
      if (!this.lastSort || this.lastSort !== key) {
        // 首次排序
        this.sort = key
        sortValue = 'desc'
      } else {
        sortValue = this.getNextSortValue()
      }

      if (!sortValue) {
        // 清空
        this.sort = ''
        this.lastSort = ''
      } else {
        this.lastSort = key
      }
      this.sortValue = sortValue
      // 刷新数据
      this.getData()
    }
  }
}
</script>

<style scoped>
/* miniprogram/pages/foundearnings.wxss */
.grid {
  display: grid;
  grid-template-columns: 50% 25% 25%;
}

.addFundInpput {
  height: 40px;
  line-height: 40px;
  border: 1px solid #eee;
  margin: 10px;
  padding-left: 5px;
}

.addFundButton {
  background: #eb565c;
  color: #fff !important;
  font-size: 20px;
  font-weight: bolder;
  border: #eb565c;
  letter-spacing: 10px;
  border-radius: 5px;
}

.fixed-bottom {
  position: fixed;
  bottom: 0;
  width: 100%;
  height: 65px;
}

.real_earningText {
  color: #1989fa;
  border: 1px solid #1989fa;
  font-size: 11px;
  width: 50px;
  line-height: 20px;
}

.isUpdated {
  width: 20px;
  margin: 0 auto;
  /* line-height: 24px; */
  font-size: 12px;
}
</style>